<template>
  <el-dialog
    v-model="dialogVisible"
    title="延期通知配置"
    width="900px"
    :before-close="handleClose"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    :show-close="true"
    :destroy-on-close="false"
    style="z-index: 9999;"
  >
    <el-form
      ref="formRef"
      :model="localForm"
      label-width="120px"
      size="default"
    >
      <!-- 基础筛选条件 -->
      <el-card class="config-section" shadow="never">
        <template #header>
          <span><el-icon><Filter /></el-icon> 筛选条件</span>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="月份:">
              <el-input v-model="localForm.workTime" placeholder="如：2024-01" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分类:">
              <el-select v-model="localForm.className" placeholder="请选择分类" clearable>
                <el-option
                  v-for="item in classNameOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区域:">
              <el-select v-model="localForm.workAreaId" placeholder="请选择区域" clearable>
                <el-option
                  v-for="item in workAreaOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="通知类型:">
              <el-radio-group v-model="localForm.notificationType">
                <el-radio :label="1">开工延期</el-radio>
                <el-radio :label="2">完工延期</el-radio>
                <el-radio :label="3">全部延期</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="延期等级:">
              <el-checkbox-group v-model="localDelayLevels" @change="handleDelayLevelsChange">
                <el-checkbox :label="1">轻微延期(1-3天)</el-checkbox>
                <el-checkbox :label="2">中等延期(4-7天)</el-checkbox>
                <el-checkbox :label="3">严重延期(>7天)</el-checkbox>
                <el-checkbox :label="4">全部等级</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 接收人配置 -->
      <el-card class="config-section" shadow="never">
        <template #header>
          <span><el-icon><User /></el-icon> 接收人配置</span>
        </template>

        <el-form-item label="配置模式:">
          <el-radio-group v-model="localForm.recipientMode" @change="handleRecipientModeChange">
            <el-radio :label="1">自动按权限配置</el-radio>
            <el-radio :label="2">指定用户</el-radio>
            <el-radio :label="3">指定角色</el-radio>
            <el-radio :label="4">混合模式</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 指定用户 -->
        <el-form-item 
          v-if="localForm.recipientMode === 2 || localForm.recipientMode === 4"
          label="指定用户:"
        >
          <el-select
            v-model="localForm.specificUserIds"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请选择用户"
            :remote-method="searchUsers"
            :loading="userSearchLoading"
            style="width: 100%"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.value"
              :label="`${user.label}${user.phone ? ` (${user.phone})` : ''}`"
              :value="user.value"
            />
          </el-select>
        </el-form-item>

        <!-- 指定角色 -->
        <el-form-item 
          v-if="localForm.recipientMode === 3 || localForm.recipientMode === 4"
          label="指定角色:"
        >
          <el-select
            v-model="localForm.specificRoleIds"
            multiple
            filterable
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="`${role.label}${role.code ? ` (${role.code})` : ''}`"
              :value="role.value"
            />
          </el-select>
        </el-form-item>

        <!-- 包含下级用户 -->
        <el-form-item 
          v-if="localForm.recipientMode === 3 || localForm.recipientMode === 4"
          label=""
        >
          <el-checkbox v-model="localForm.includeSubordinates">
            包含所选角色用户的下级用户
          </el-checkbox>
        </el-form-item>

        <el-form-item label="">
          <el-button 
            type="primary" 
            :loading="previewLoading"
            @click="handlePreview"
          >
            预览接收人
          </el-button>
          <span style="margin-left: 10px; color: #666; font-size: 12px;">
            发送前可以预览具体的通知接收人列表
          </span>
        </el-form-item>
      </el-card>

      <!-- 自定义消息 -->
      <el-card class="config-section" shadow="never">
        <template #header>
          <span><el-icon><EditPen /></el-icon> 消息内容</span>
        </template>

        <el-form-item label="自定义消息:">
          <el-input
            v-model="localForm.customMessage"
            type="textarea"
            :rows="3"
            placeholder="留空使用默认消息模板。支持变量：{WorkAreaName}, {TotalCount}, {SevereCount}, {MediumCount}, {LightCount}"
          />
        </el-form-item>
      </el-card>

      <!-- 预览结果 -->
      <el-card v-if="preview" class="config-section" shadow="never">
        <template #header>
          <span><el-icon><View /></el-icon> 预览结果</span>
        </template>

        <el-alert 
          :title="preview.message"
          :type="preview.success ? 'success' : 'warning'"
          show-icon
          :closable="false"
          style="margin-bottom: 15px"
        />

        <div v-if="preview.success && preview.workAreas.length > 0">
          <el-descriptions :column="3" border size="small" style="margin-bottom: 15px">
            <el-descriptions-item label="延期项目总数">{{ preview.totalDelayItemCount }}</el-descriptions-item>
            <el-descriptions-item label="涉及区域数">{{ preview.affectedWorkAreaCount }}</el-descriptions-item>
            <el-descriptions-item label="通知人数">{{ preview.totalRecipientCount }}</el-descriptions-item>
          </el-descriptions>

          <el-tabs v-model="activeTab" type="border-card">
            <el-tab-pane
              v-for="(area, index) in preview.workAreas"
              :key="index"
              :label="`${area.workAreaName} (${area.recipients.length}人)`"
              :name="`area-${index}`"
            >
              <el-table :data="area.recipients" size="small" height="200">
                <el-table-column prop="userName" label="姓名" width="120" />
                <el-table-column prop="account" label="账号" width="120" />
                <el-table-column prop="phone" label="手机号" width="130" />
                <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          :loading="loading"
          :disabled="!preview || !preview.success || preview.totalRecipientCount === 0"
          @click="handleConfirm"
        >
          发送通知
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { Filter, User, EditPen, View } from '@element-plus/icons-vue'

// Props
interface Props {
  visible: boolean
  formData: any
  preview: any
  loading: boolean
  previewLoading: boolean
  userOptions: any[]
  roleOptions: any[]
  classNameOptions: any[]
  workAreaOptions: any[]
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
})

// Emits
const emit = defineEmits(['update:visible', 'preview', 'confirm', 'update:formData'])

// 创建响应式的 visible 属性
const dialogVisible = computed({
  get: () => {
    console.log('获取对话框可见性:', props.visible);
    return props.visible;
  },
  set: (value: boolean) => {
    console.log('设置对话框可见性:', value);
    emit('update:visible', value);
  }
})

// Refs
const formRef = ref()
const activeTab = ref('area-0')
const userSearchLoading = ref(false)

// 本地表单副本 + 与父级双向同步
const clone = (obj: any) => JSON.parse(JSON.stringify(obj ?? {}))
const localForm = ref<any>(clone(props.formData))
watch(
  () => props.formData,
  (v) => {
    localForm.value = clone(v)
    // 同步本地的延迟等级显示
    localDelayLevels.value = Array.isArray(localForm.value.delayLevels) ? [...localForm.value.delayLevels] : []
  }
)

// 处理对话框关闭
const handleClose = () => {
  dialogVisible.value = false
}

// 处理接收人模式变化
const handleRecipientModeChange = () => {
  // 清空之前的选择
  localForm.value.specificUserIds = []
  localForm.value.specificRoleIds = []
  emit('update:formData', clone(localForm.value))
}

// 延期等级互斥处理
const prevLevels = ref<number[]>(Array.isArray(props.formData?.delayLevels) ? [...props.formData.delayLevels] : [])
const localDelayLevels = ref<number[]>(Array.isArray(localForm.value?.delayLevels) ? [...localForm.value.delayLevels] : [])
const handleDelayLevelsChange = (levels: number[]) => {
  const oldSet = new Set(prevLevels.value)
  const added = levels.filter(v => !oldSet.has(v))

  // 空选择 -> 默认选中“全部等级”
  let next: number[] = levels
  if (levels.length === 0) {
    next = [4]
  } else {
    const hasAll = levels.includes(4)
    const hasSpecific = levels.some(v => v === 1 || v === 2 || v === 3)
    const addedHasAll = added.includes(4)
    const addedHasSpecific = added.some(v => v === 1 || v === 2 || v === 3)

    if (hasAll && hasSpecific) {
      if (addedHasAll) {
        next = [4]
      } else if (addedHasSpecific) {
        next = levels.filter(v => v !== 4)
      } else {
        next = levels.filter(v => v !== 4)
      }
    }
  }

  // 更新本地与父级
  localDelayLevels.value = [...next]
  prevLevels.value = [...next]
  localForm.value.delayLevels = [...next]
  emit('update:formData', clone(localForm.value))
}

// 搜索用户
const searchUsers = (query: string) => {
  if (query) {
    userSearchLoading.value = true
    // 这里应该调用API搜索用户
    setTimeout(() => {
      userSearchLoading.value = false
    }, 500)
  }
}

// 预览接收人
const handlePreview = () => {
  emit('update:formData', clone(localForm.value))
  emit('preview')
}

// 确认发送
const handleConfirm = () => {
  emit('update:formData', clone(localForm.value))
  emit('confirm')
}
</script>

<style scoped lang="scss">
.config-section {
  margin-bottom: 20px;
  
  :deep(.el-card__header) {
    padding: 12px 20px;
    background-color: #f8f9fa;
    
    span {
      font-weight: 600;
      color: #303133;
      
      .el-icon {
        margin-right: 5px;
        vertical-align: middle;
      }
    }
  }
  
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.dialog-footer {
  text-align: right;
}

:deep(.el-descriptions__label) {
  width: 120px;
}

:deep(.el-tabs__content) {
  padding: 15px;
}
</style>